include Java
require 'gookup/common/usefull_extensions'
require 'gookup/system/settings_container'
require 'gookup/gmail/model/gmail_model'
# based upon http://forum.java.sun.com/thread.jspa?threadID=5244174&tstart=1
IMAP={"mail.imap.socketFactory.class"=>'javax.net.ssl.SSLSocketFactory', "mail.imap.socketFactory.fallback"=>"false", "mail.imap.port"=>"993", "mail.imap.socketFactory.port"=>"993"}
Dependcies=['java.util.Properties', 'java.security', 'com.sun.net.ssl.internal.ssl.Provider', 'java.lang', 'javax.mail', 'javax.mail.internet', 'java.io']
JProps=java.util.Properties

class Gmail
    Dependcies.each { |d| include_package(d) }

    attr_reader :store,:model

    def initialize
        Security.addProvider(com.sun.net.ssl.internal.ssl.Provider.new())
        props = System.properties
        IMAP.each { |k, v| props.setProperty(k, v) }
        @session = Session.getDefaultInstance(props, nil)
        @model=GmailModel.new
    end

    def login(user, pass)
        begin
            urln =  URLName.new("imap", "imap.gmail.com", 993, nil, user, pass)
            @store = @session.getStore(urln)
            @store.connect
            @model.store = @store
        rescue AuthenticationFailedException => e
            @store=nil
            raise Exception.new('failed to login into gmail!')
        end
    end

    def fetch_inbox_data
        @model.fetch_inbox_data
    end

    def persist
        @model.persist
    end
end
